//
//  HELCourseDetailVC.m
//  sanda
//
//  Created by wsj2015 on 16/7/12.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "HELCourseDetailVC.h"

#import "CSStickyHeaderFlowLayout.h"
#import "CouresDetailSegmentCell.h"

#import "KLCPopup.h"
#import "HCSStarRatingView.h"
#import "HELStarRatingAlert.h"

#import "UICollectionView+ARDynamicCacheHeightLayoutCell.h"
#import "HELCourseCommentCell.h"

#import "MJRefresh.h"
#import "HELNetworkManager.h"

#import "HELCourseCommentModel.h"
#import "HELAppManager.h"
#import "UIScrollView+WSJRefresh_MJ.h"
#import "ReaderFileViewController.h"
#import "WCNMulTextEditVC.h"
#import "AppDelegate.h"
#import "HELPrepareForExamVC.h"
#import "HYBBubbleTransition.h"
#import "CourseDetailHeaderPax.h"
#import "HELCourseInformationCell.h"
#import "WSJPopview.h"
#import "ReamlDataTool.h"
#import "HELPDFfileCacheTool.h"

#define HEADER_HEIGHT 254
@interface HELCourseDetailVC ()<UICollectionViewDataSource,UICollectionViewDelegate,UITextFieldDelegate,UIViewControllerTransitioningDelegate>

@property (nonatomic,  strong) UICollectionView *collectView;

@property (nonatomic,  strong) NSMutableArray *commentDataArray;

@property (nonatomic,  assign) NSInteger currentSelectIndex;



@property (nonatomic, strong) HELCourseDetailModel *courseModel;

@property (nonatomic,  strong) UIButton *collectBtn;

@property (nonatomic,  strong) UIView *commentInputView;

@property (nonatomic,  strong) UITextField *inputTf;

@property (nonatomic,  strong)HYBBubbleTransition* bubbleTransition ;

@property (nonatomic,  assign) CGRect collectBtnFrame;


//@property (nonatomic,  strong) UIView *navCover;



@end

@implementation HELCourseDetailVC

- (instancetype)init
{
    self = [super init];
    if (self) {
     
    
       
    }
    return self;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    if ([object isKindOfClass:[UITextField class]]) {
        NSString *new =change[@"new"];
        UIButton *btn = [self.inputView viewWithTag:801];
        if (!new && [new isEqualToString:@""]) {
            btn.enabled = NO;
           
        }else{
            btn.enabled = YES;
        }
    }
    
    if ([keyPath isEqualToString:@"currentSelectIndex"]) {
        NSNumber *new= change[@"new"];
         weakSelf_define;
        if ([new integerValue] == 0) {
           
            [UIView animateWithDuration:.35f animations:^{
                weakSelf.commentInputView.frame =CGRectMake(0, kScreenHeight-64, kScreenWidth, 39);
                weakSelf.collectView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight -64);
            }];
            
        }else{
            
            [UIView animateWithDuration:.35f animations:^{
                weakSelf.commentInputView.frame = CGRectMake(0, kScreenHeight-49 -64, kScreenWidth, 49);
                weakSelf.collectView.frame =CGRectMake(0, 0, kScreenWidth, kScreenHeight- 64 -33);
            }];
        
        
        }
    }
}

- (void)viewDidDisappear:(BOOL)animated{

    [super viewDidDisappear:animated];
    if (self.callBack) {
        self.callBack(self.courseModel);
    }
        
    
}

- (void)dealloc{
//    [self removeObserver:self forKeyPath:@"currentSelectIndex"];
//    [self.inputTf removeObserver:self forKeyPath:@"text"];
}
- (NSMutableArray *)commentDataArray{
    if (!_commentDataArray) {
        _commentDataArray = [NSMutableArray array];
    }
    return _commentDataArray;

}


- (UICollectionView *)collectView{
    if (!_collectView) {
        
       
        NSInteger headerHgiht = HEADER_HEIGHT;
        if (kScreenWidth == 320 && kScreenHeight ==480) {//iphone4
            
        }else if(kScreenWidth == 320 && kScreenHeight ==568){ //iphone 5
            
        }else if(kScreenWidth == 375 && kScreenHeight == 667){ //iphone 6
            
        }else if(kScreenWidth == 414 && kScreenHeight == 736){ //iphone 6P
            headerHgiht +=44;
        }
        
        
        
        
        CSStickyHeaderFlowLayout *layout =[[CSStickyHeaderFlowLayout alloc]init];
        layout.parallaxHeaderReferenceSize = CGSizeMake(self.view.frame.size.width, 210);
        layout.parallaxHeaderMinimumReferenceSize = CGSizeMake(self.view.frame.size.width,0.0);
//        layout.itemSize = CGSizeMake(kScreenWidth, 300);
        layout.parallaxHeaderAlwaysOnTop = YES;
        
        // If we want to disable the sticky header effect
        layout.disableStickyHeaders = YES;
        
        
        CGFloat space = 8;
        
        layout.sectionInset =UIEdgeInsetsMake(4, space, 8, space);
        layout.minimumInteritemSpacing = 0;
        layout.minimumLineSpacing = 8;
        CGRect frame =CGRectMake(0, 0, kScreenWidth, kScreenHeight- 64);
        _collectView =[[UICollectionView alloc]initWithFrame:frame collectionViewLayout:layout];
        _collectView.delegate = self;
        _collectView.dataSource = self;
        _collectView.showsVerticalScrollIndicator = NO;
        _collectView.alwaysBounceVertical =YES;
        _collectView.backgroundColor = kAppBg;
        //
        if ([_collectView respondsToSelector:@selector(setPrefetchingEnabled:)]) {
            _collectView.prefetchingEnabled = NO;
        }
        
        
    }
    return _collectView;
    
}
- (UIView *)commentInputView{
    if (!_commentInputView) {
        _commentInputView =[[UIView alloc] init];
        _commentInputView.frame =CGRectMake(-2, kScreenHeight, kScreenWidth +4, 49);
        UITextField *tf =[[UITextField alloc] init];
        tf.frame = CGRectMake(25, 11, kScreenWidth -100, 30);
        tf.delegate = self;
        tf.placeholder = @"我也评论一句";
        self.inputTf = tf;
        tf.borderStyle = UITextBorderStyleRoundedRect;
        _commentInputView.layer.borderWidth =1;
        _commentInputView.layer.borderColor = kBorderColor.CGColor;
        [_commentInputView addSubview:tf];
        
        UIButton *btn =[UIButton buttonWithType:UIButtonTypeSystem];
        btn.frame = CGRectMake(CGRectGetMaxX(tf.frame)+8,11, 64, 30);
        btn.tag = 801;
        [btn setBackgroundColor:kMainColor];
        btn.titleLabel.font = [UIFont systemFontOfSize:15];
        [btn setTitle:@"发送" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn setTitleColor:kTxtColor forState:UIControlStateDisabled];
        wsj_cornerRadius(btn, 8);
//        [btn addTarget:self action:@selector(giveCommentScoreWith:) forControlEvents:UIControlEventTouchUpInside];
        [_commentInputView addSubview:btn];
        
        _commentInputView.backgroundColor = kAppBg;
    }
    return _commentInputView;
}

#pragma mark -开始写评论
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    weakSelf_define;
    WCNMulTextEditVC *vc =[[WCNMulTextEditVC  alloc] initWithType:0];
    vc.canEmpty = NO;
    vc.title =@"写评论";
    vc.textViewPlaceholder = @"评论内容";
    vc.textViewValue =textField.text;
    vc.limitCount = 80;
    vc.callback = ^(NSString *content){
        [weakSelf sendCommentWith:content];
    };
    [self.navigationController pushViewController:vc animated:YES];
    return NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self setNavToBlue];
    [self requesetSdutyDetailData];
  
    
    [self addObserver:self forKeyPath:@"currentSelectIndex" options:NSKeyValueObservingOptionNew context:nil];
   
}



- (void)configUI{
    
    self.currentSelectIndex = 0;
    
     [self titleView:@"课程详情"];
    [self.view addSubview:self.collectView];
    
    [self.view addSubview:self.commentInputView];

     [self.inputTf addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew context:nil];
    
    [self.collectView registerNib:[UINib nibWithNibName:@"CourseDetailHeaderPax" bundle:nil]
       forSupplementaryViewOfKind:CSStickyHeaderParallaxHeader
              withReuseIdentifier:@"CourseDetailHeaderPax"];
    [self.collectView registerNib:[UINib nibWithNibName:@"CouresDetailSegmentCell" bundle:nil] forCellWithReuseIdentifier:@"CouresDetailSegmentCell"];
    [self.collectView registerNib:[UINib nibWithNibName:@"HELCourseCommentCell" bundle:nil] forCellWithReuseIdentifier:@"HELCourseCommentCell"];
    
    [self.collectView registerNib:[UINib nibWithNibName:@"HELCourseInformationCell" bundle:nil] forCellWithReuseIdentifier:@"HELCourseInformationCell"];
//        UIBarButtonItem *ratingItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_collect"]landscapeImagePhone: style:UIBarButtonItemStyleDone target:self action:@selector(clickCollect)];
    
    
//    UIBarButtonItem *ratingItem1 = [[UIBarButtonItem alloc] initWithTitle:@"评分" style:0 target:self action:@selector(clickRating)];
    
    UIBarButtonItem *ratingItem =[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"rating_icon"] style:0 target:self action:@selector(clickRating)];
    
    UIButton *collectBtn =[UIButton buttonWithType:UIButtonTypeCustom];
    collectBtn.frame =CGRectMake(0, 0, 25, 25);
    [collectBtn setImage:[UIImage imageNamed:@"collect_icon"] forState:UIControlStateNormal];
    [collectBtn setImage:[UIImage imageNamed:@"collect_icon_ed"] forState:UIControlStateSelected];
    [collectBtn addTarget:self action:@selector(collectCourseAndUpdateBtnStatue:) forControlEvents:UIControlEventTouchUpInside];
    self.collectBtn = collectBtn;
    
    UIBarButtonItem *collectItem =[[UIBarButtonItem alloc] initWithCustomView:collectBtn];
    
    NSMutableArray *array =[NSMutableArray arrayWithObjects:ratingItem, collectItem,nil];
    
   
    self.navigationItem.rightBarButtonItems = array;
    self.collectBtn.alpha = 0;
    
    defineWeakSelf;
    
    [self.collectView wsj_HeaderRefreshBlock:^{
        if (weakSelf.currentSelectIndex ==0) {
            [weakSelf requesetSdutyDetailData];
        }else{
            [weakSelf requesetCommentData:YES];
        }
    }];
    [self.collectView addLegendFooterWithRefreshingBlock:^{
        if (weakSelf.currentSelectIndex ==1) {[weakSelf requesetCommentData:NO];}
    }];
    self.collectView.footer.hidden =YES;
    
    
    
}
#pragma mark 更新收藏状态

//- (void)updateCollectSate{
//
//    self.collectBtn.selected = [self.courseModel.collectStatus integerValue]?NO:YES;
//    
//}

#pragma mark -或缺详情
- (void)requesetSdutyDetailData{
    
    weakSelf_define ;
    
    if (!self.courseModel) {
      [self wsj_showLodingGif];
    }
    

    NSMutableDictionary *params =[NSMutableDictionary dictionary];
//    params[@"id"] = @(76);
    params[@"id"] =@(self.courseId);

    
    params[@"userId"] =HEL_USERID;
    [[HELNetworkManager sharedMg] GET:kSdutyDetail_url parameters:params success:^(NSDictionary * responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            weakSelf.courseModel =[HELCourseDetailModel mj_objectWithKeyValues:responseObject];
            
            [UIView animateWithDuration:.35 animations:^{
                weakSelf.collectBtn.alpha = 1;
            }];

            weakSelf.collectBtn.selected = [weakSelf.courseModel.collectStatus integerValue]==1?YES:NO;
            [weakSelf.collectView reloadData];
            
            if (weakSelf.courseModel) {
//                如果存在文件 则更新数据库
                NSString *filePath =[HELPDFfileCacheTool isChchedWithPdfFilename:weakSelf.courseModel.pdfName];
                if (filePath) {
                    [[ReamlDataTool  sharedTool]updateCourseWithCourse:weakSelf.courseModel];
                }
            }
//
           
            
           
        }
        if (responseObject[@"exception"]) {
            alertMessage(responseObject[@"exception"]);
        }
        
          [weakSelf wsj_hideLodingGif];
       // [weakSelf stopAnimationTitle];
        [weakSelf.collectView.header endRefreshing];
     } failure:^(NSString *err) {
//        // [weakSelf stopAnimationTitle];
        [weakSelf.collectView.header endRefreshing];
         
         if (!weakSelf.courseModel) {
             [weakSelf wsj_hideLodingGif];
             [weakSelf.navigationController popViewControllerAnimated:YES];
         }
       
     }];

}
#pragma mark -获取评论
- (void)requesetCommentData:(BOOL)isRecover{

    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    //    params[@"id"] = @(76);
    params[@"tblStudyDataId"] =@(self.courseId);
    params[@"pageSize"] =@(10);
    
    
    static  NSInteger currentPage =1;
    
    if (isRecover) {
        currentPage =1;
    }else{
        currentPage ++;
    }
    params[@"currentPage"] =@(currentPage);
//    defineWeakSelf;
//    [self startAnimationTitle];
    NSLog(@"----%d",currentPage);
    defineWeakSelf;
    [[HELNetworkManager sharedMg] GET:kCoureCommmets_url parameters:params success:^(NSDictionary *responseObject) {
        
        if (isRecover) {
            [weakSelf.commentDataArray removeAllObjects];
        }
        if (responseObject[@"exception"]) {
            alertMessage(responseObject[@"exception"]);
        }else
            if ([responseObject[@"rows"] isKindOfClass:[NSArray class]]) {
                [weakSelf.commentDataArray addObjectsFromArray:[HELCourseCommentModel mj_objectArrayWithKeyValuesArray:responseObject[@"rows"]]];
            }
        
//       // [weakSelf stopAnimationTitle];
        [weakSelf.collectView.header endRefreshing];
        [weakSelf.collectView.footer endRefreshing];
        
//        if ([responseObject[@"pages"] integerValue] ==0 || currentPage ==[responseObject[@"pages"] integerValue]) {
////            [weakSelf.collectView removeFooter];
//        }else{
//            [weakSelf.collectView addLegendFooterWithRefreshingBlock:^{
//                if (weakSelf.currentSelectIndex ==1) {[weakSelf requesetCommentData:NO];}
//            }];
//        }
        
        [weakSelf.collectView reloadData];
    } failure:^(NSString *err) {
       // [weakSelf stopAnimationTitle];
        [weakSelf.collectView.header endRefreshing];
         [weakSelf.collectView.footer endRefreshing];
    }];
    
}
#pragma mark -评分
- (void)giveCommentScoreWith:(CGFloat )score{
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    cwqHud(self.view);
    params[@"tblStudyDataId"] =@(self.courseId);
//    {score = 8,tblStudyDataId = 76}
    params[@"score"] =@(score);
    params[@"userId"] =HEL_USERID;
    weakSelf_define;
    [[HELNetworkManager sharedMg] GET:kCourseScoring_url parameters:params success:^(id responseObject) {
        if (responseObject[@"exception"]) {
            alertMessage(responseObject[@"exception"]);
        }else{
            weakSelf.courseModel.scoreAvg =[NSString stringWithFormat:@"%@",@(score)];
            weakSelf.courseModel.isScore =[NSString stringWithFormat:@"%@",@(YES)];
            alertMessage(@"评分成功!感谢您的参与~");
            [weakSelf requesetSdutyDetailData];
        }
        [hud hideAnimated:YES];
    } failure:^(NSString *err) {
        [hud hideAnimated:YES];
    }];
}

#pragma mark -收藏请求
- (void)collectCourseAndUpdateBtnStatue:( UIButton *)btn{
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    cwqHud(self.view);
  
    params[@"ids"] = [self jsonStringWithArray:@[@(self.courseId)]];

    //    {score = 8,tblStudyDataId = 76}
    params[@"userId"]=HEL_USERID;
    weakSelf_define;
    [[HELNetworkManager sharedMg] GET:kCourseCollect_url parameters:params success:^(id responseObject) {
        if ([responseObject isKindOfClass:[NSArray class]]) {
            NSArray *resArr = responseObject;
            NSDictionary *dict =resArr.lastObject;
            if ([dict[@"collectStatus"] integerValue]==0) {
                cwqAlertMessage(@"取消收藏成功!~");
                weakSelf.courseModel.collectStatus = [NSString stringWithFormat:@"%@",@(0)];
                btn.selected = NO;
            }else if([dict[@"collectStatus"] integerValue]==1) {
                weakSelf.courseModel.collectStatus = [NSString stringWithFormat:@"%@",@(1)];
                btn.selected = YES;
                cwqAlertMessage(@"收藏成功!~");
            }else {
               
                cwqHudSuccess(hud);
            }
            

            
        }else {
            if (responseObject[@"exception"]) {
                cwqAlertMessage(responseObject[@"exception"]);
            }
        }
        
    } failure:^(NSString *err) {
        [hud hideAnimated:YES];
    }];

}
-(NSString *)jsonStringWithArray:(NSArray *)array{
    NSString *string = [NSString stringWithFormat:@"%@",array];
    NSString * str = [string stringByReplacingOccurrencesOfString:@"(" withString:@"["];
    NSString *str2 = [str stringByReplacingOccurrencesOfString:@")" withString:@"]"];
    return str2;
}
#pragma mark -发送评论
- (void)sendCommentWith:(NSString *)content{
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    cwqHud(self.view);
    params[@"tblStudyDataId"] =@(self.courseId);
    //    {score = 8,tblStudyDataId = 76}
    params[@"userId"]=HEL_USERID;
    params[@"content"]=content;
 
    weakSelf_define;
    
    [[HELNetworkManager sharedMg] POST:kCourseSendComment parameters:params success:^(id responseObject) {
        if (responseObject[@"exception"]) {
            alertMessage(responseObject[@"exception"]);
        }
        if (responseObject[@"content"]) {
        
            [weakSelf requesetCommentData:YES];
                  }
       
        [hud hideAnimated:YES];
    } failure:^(NSString *err) {
        [hud hideAnimated:YES];
    }];


}
//#pragma mark -点赞
//- (void)praiseCommentWithCommentModel:(NSInteger)commentId indexPath:(NSIndexPath *)indexPath type:(NSInteger)type{
//   
//    NSMutableDictionary *params =[NSMutableDictionary dictionary];
//    cwqHud(self.view);
//    params[@"id"] =@(commentId);
//    //    {score = 8,tblStudyDataId = 76}
//    params[@"type"]=@(type);
//    params[@"userId"]=HEL_USERID;
//    weakSelf_define;
//    HELCourseCommentModel *model= self.commentDataArray[indexPath.item];
//    if (type ==0) {
//        NSInteger good = [model.goodNum integerValue];
//        model.goodNum =[NSString stringWithFormat:@"%@",@(good+1)];
//    }else{
//        NSInteger bad = [model.badNum integerValue];
//        model.badNum =[NSString stringWithFormat:@"%@",@(bad+1)];
//    }
//    [[HELNetworkManager sharedMg] GET:kPraiseComment parameters:params success:^(id responseObject) {
//        if ([responseObject[@"root"] isKindOfClass:[NSString class]]) {
////            alertMessage(responseObject[@"root"]);
//            
//            [weakSelf.collectView reloadItemsAtIndexPaths:@[indexPath]];
//        }
//        
//        
//        [hud hideAnimated:YES];
//    } failure:^(NSString *err) {
//        [hud hideAnimated:YES];
//    }];
//    
//
//    
//}

//- (DCCommentView *)commentView{
//    if (!_commentView) {
//       _commentView = [[DCCommentView alloc] initWithScrollView:self.collectView frame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
//        _commentView.delegate = self;
//        _commentView.backgroundColor = kAppBg;
//        
//
//    }
//    return _commentView;
//
//}


//- (void)updateCollect

#pragma mark -Action
 
//- (void)clickCollect{
//    
//    [self collectCourse];
//    
//    
//}
- (void)clickRating{
    
    
//    [WSJPopview sharedWsjPopView] showRatingView:<#(BOOL)#> withHelpScore:<#(CGFloat)#> withContentScore:<#(CGFloat)#> withDoneBlock:<#^(CGFloat help_score, CGFloat content_score)doneBlock#>
//    
    HELStarRatingAlert *ratingView =[[HELStarRatingAlert alloc] initWithFrame:CGRectMake(0, 0, 240, 120)];
    
    ratingView.backgroundColor = [UIColor whiteColor];
    ratingView.isAllowEdit = YES;
    
    weakSelf_define;
    KLCPopup *pop =  [KLCPopup popupWithContentView:ratingView showType:KLCPopupShowTypeSlideInFromTop dismissType:KLCPopupDismissTypeGrowOut maskType:KLCPopupMaskTypeDimmed dismissOnBackgroundTouch:YES dismissOnContentTouch:NO];
    __weak typeof(pop) weakPop = pop;
    
    
    //没有打过分
    if ([self.courseModel.isScore integerValue]==0) {
        ratingView.callBack = ^(CGFloat rating){
            [weakPop dismiss:YES];
            [weakSelf giveCommentScoreWith:rating * 2];
        };
        
    }else{
        
        //      已经打过分
        ratingView.customTitle  =[NSString stringWithFormat:@"您已给出了评分:%.f分", [self.courseModel.scoreAvg floatValue]];
        CGFloat f = [self.courseModel.scoreAvg floatValue]/2;
        ratingView.rating = f;
        ratingView.isAllowEdit = NO;
        ratingView.callBack = ^(CGFloat rating){
            [weakPop dismiss:YES];
           
        };
        
        
    }
   
    [pop show];

}
                                    
                                    
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{

    if (self.currentSelectIndex==1) {
//         [self.commentView endEditing:YES];
    }
   
  
}
#pragma mark UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    //    return [self.dataArray count];
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    //    NSArray *arr = self.dataArray[section];/
  
    if (self.currentSelectIndex==0) {
        return 1;
    }
    NSLog(@"++++++%d",self.commentDataArray.count);
    return self.commentDataArray.count;
    //    return arr.count;
}
-(void)didSendComment:(NSString *)text
{
    [self sendCommentWith:text];
}


#pragma mark -马上恢复竖屏
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
 

   
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
 
  

}
#pragma mark -显示cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    weakSelf_define;
    if (self.currentSelectIndex==0) {
      __weak  HELCourseInformationCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"HELCourseInformationCell" forIndexPath:indexPath];
        cell.model =self.courseModel;
        cell.playBlock = ^(){
            
            [weakSelf gotoPdfVCWith:cell];
        };
        cell.examBlock =^(){
            HELPrepareForExamVC *vc =[[HELPrepareForExamVC alloc] initWithExamId:[NSString stringWithFormat:@"%@",self.courseModel.tblExamId]];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
        cell.moreBlock = ^(){
           
            [UIView performWithoutAnimation:^{
                 [collectionView reloadItemsAtIndexPaths:@[ [NSIndexPath indexPathForItem:0 inSection:0]]];
            }];
           
        
        };
        
        //根据课程数据库查询 该pdf 是否已经完成下载
        
        
         NSString *filePath =[HELPDFfileCacheTool isChchedWithPdfFilename:weakSelf.courseModel.pdfName];
        if (filePath) {
            [cell.downBtn setTitle:@"已下载" forState:UIControlStateNormal];
            cell.downBtn.enabled = NO;
        }else{
            [cell.downBtn setTitle:@"下载" forState:UIControlStateNormal];
            cell.downBtn.enabled = YES;
            cell.downloadBlock = ^(){
                
                
                WSJPopview *downPop = [[WSJPopview sharedWsjPopView] showDownLoadWithUrl:weakSelf.courseModel.pdfNameShow withPdfName:weakSelf.courseModel.pdfName];
                downPop.doneBlock = ^(){
                    [cell.downBtn setTitle:@"已下载" forState:UIControlStateNormal];
                    cell.downBtn.enabled = NO;
                    
                  
                    //更新数据库
                    [[ReamlDataTool  sharedTool]updateCourseWithCourse:weakSelf.courseModel];
                    
                };
                
            };

        
        }
        
      
        return cell;
    }else{
        __weak HELCourseCommentCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"HELCourseCommentCell" forIndexPath:indexPath];
        HELCourseCommentModel *comment =self.commentDataArray[indexPath.row];
        cell.model = self.commentDataArray[indexPath.row];
//        cell.praiseBlock = ^(){
//            [weakSelf praiseCommentWithCommentModel:[comment.id integerValue] indexPath:indexPath  type:0];
//        };
//        cell.unPraiseBlock =^(){
//         [weakSelf praiseCommentWithCommentModel:[comment.id integerValue] indexPath:indexPath type:1];
//        };
        return cell;
    }
    
    
        
//    }
//    return nil;
  
}
- (void)gotoPdfVCWith:(HELCourseInformationCell *)cell{
    
    ReaderFileViewController *fileViewController = [[ReaderFileViewController alloc] init];
//    

    fileViewController.title = self.courseModel.name;
    fileViewController.urlStr =self.courseModel.pdfNameShow;
    fileViewController.courseId = self.courseId;
    fileViewController.pdfName = self.courseModel.pdfName;
    fileViewController.modalPresentationStyle = UIModalPresentationFullScreen;
    defineWeakSelf;
    fileViewController.callBack = ^(){
      
        [weakSelf requesetSdutyDetailData];
    
        
    };
    
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:fileViewController];
    [navigationController.navigationBar setTintColor:[UIColor whiteColor]];
 
    navigationController.navigationBar.translucent = YES;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>8.0) {
        navigationController.modalPresentationStyle = UIModalPresentationCustom;
        self.bubbleTransition =[[HYBBubbleTransition alloc] initWithPresented:^(UIViewController *presented, UIViewController *presenting, UIViewController *source, HYBBaseTransition *transition) {
            // You need to cast type to the real subclass type.
            HYBBubbleTransition *bubble = (HYBBubbleTransition *)transition;
            
            // If you want to use Spring animation, set to YES.
            // Default is NO.
            //    bubble.animatedWithSpring = YES;
            bubble.bubbleColor = kMainColor;
            //                      bubble.animatedWithSpring = YES;
            // 由于一个控制器有导航，一个没有，导致会有64的误差
            CGPoint startPoint = [cell.playImage convertPoint:cell.playImage.center toView:self.view];
            startPoint.y +=64;
            bubble.bubbleStartPoint = startPoint;
        } dismissed:^(UIViewController *dismissed, HYBBaseTransition *transition) {
            
            transition.transitionMode = kHYBTransitionDismiss;
        }];
        navigationController.transitioningDelegate =  self.bubbleTransition;
        
    }
    
    [self presentViewController:navigationController animated:YES completion:NULL];
    

 
}


#pragma mark - flowlayout

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    weakSelf_define;
    if (self.currentSelectIndex ==0) {
        return [collectionView ar_sizeForCellWithIdentifier:@"HELCourseInformationCell" indexPath:indexPath fixedWidth:kScreenWidth configuration:^(__kindof HELCourseInformationCell *cell) {
            
            cell.model =weakSelf.courseModel;
        }];
//        return CGSizeMake(kScreenWidth, 185);
       
    }else{
        
        
        
//        CGSize size = [collectionView ar_sizeForCellWithIdentifier:@"HELCourseCommentCell" indexPath:indexPath configuration:^(__kindof HELCourseCommentCell *cell) {
//            cell.model = weakSelf.commentDataArray[indexPath.row];
//        }];
        
        CGSize size =[collectionView ar_sizeForCellWithIdentifier:@"HELCourseCommentCell" indexPath:indexPath fixedWidth:kScreenWidth configuration:^(__kindof HELCourseCommentCell *cell) {
            HELCourseCommentModel *model = weakSelf.commentDataArray[indexPath.row];
            cell.model = model;
           
        }];
//        NSLog(@"----%@",NSStringFromCGSize(size));
         return size;
       
    }
    
    return CGSizeMake(0, 0);
    
//    FeedModel *feed = self.feeds[indexPath.row];
//    if (self.onlyImage) {
//        return [collectionView ar_sizeForCellWithIdentifier:@"DynamicSizeCell"
//                                                  indexPath:indexPath
//                                              configuration:^(id cell) {
//                                                  [cell filleCellWithFeed:feed];
//                                              }];
//        
//    }else{
//        
//        return [collectionView ar_sizeForCellWithIdentifier:@"DynamicHeightCell"
//                                                  indexPath:indexPath
//                                                 fixedWidth:300 configuration:^(id cell) {
//                                                     [cell filleCellWithFeed:feed];
//                                                 }];
//    }
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
   
    } else if ([kind isEqualToString:CSStickyHeaderParallaxHeader]) {
        CourseDetailHeaderPax *cell = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                                            withReuseIdentifier:@"CourseDetailHeaderPax"
                                                                                   forIndexPath:indexPath];
        self.collectBtnFrame =[cell.collectBtn convertRect:cell.collectBtn.frame toView:self.view];
        if (self.isFromRequiedCourse) {
             [cell.collectBg removeFromSuperview];
            [cell.collectBtn removeFromSuperview];
        }
        defineWeakSelf;
        cell.changeSelectItem = ^(NSInteger selecetIndex){
            if (selecetIndex ==1) {
              weakSelf.collectView.footer.hidden =NO;
            if (weakSelf.commentDataArray.count==0) {
                [weakSelf requesetCommentData:YES];
            }
        }else{
            weakSelf.collectView.footer.hidden =YES;
        }
         weakSelf.currentSelectIndex = selecetIndex;
        [weakSelf.collectView reloadSections:[NSIndexSet indexSetWithIndex:0]];
        
        };
//        cell.changeBlock = ^(NSInteger selecetIndex){
//           
////            [weakSelf.commentView hideToolBarView:!selecetIndex];
//            if (selecetIndex ==1) {
//                  weakSelf.collectView.footer.hidden =NO;
//                if (weakSelf.commentDataArray.count==0) {
//                    [weakSelf requesetCommentData:YES];
//                }
//            }else{
//                weakSelf.collectView.footer.hidden =YES;
//            }
//             weakSelf.currentSelectIndex = selecetIndex;
//            [weakSelf.collectView reloadSections:[NSIndexSet indexSetWithIndex:0]];
//        };
//        cell.exameBlock = ^(NSInteger examId){
//            HELPrepareForExamVC *vc =[[HELPrepareForExamVC alloc] initWithExamId:[NSString stringWithFormat:@"%@",@(examId)]];
//            [weakSelf.navigationController pushViewController:vc animated:YES];
//            
//            
//        };
        cell.collectBlock = ^(UIButton *btn){
        
            [weakSelf collectCourseAndUpdateBtnStatue:btn];
        };
        cell.model = self.courseModel;
    
        return cell;
    }
    return nil;
}


@end
